//
//  MyInfoViewController.m
//  jingjing2.0
//
//  Created by apple on 16/4/27.
//  Copyright © 2016年 apple. All rights reserved.
//
#import "NSDate+Helper.h"
#import "MyInfoViewController.h"
#import "MyInfoTableViewCell.h"
#import "WalletViewController.h"
#import "MyAddressViewController.h"
#import "MyCouponViewController.h"
#import "MyRewardViewController.h"
#import "AboutJingjingViewController.h"
#import "AssistViewController.h"
#import "MessageCenterViewController.h"
@interface MyInfoViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    UILabel * _leftMoneyLabel;
    UILabel * _couponLabel;
    UILabel * _rewardLabel;
    NSString *_couponCount;
}
@property(nonatomic,strong)UIView   * customNavView;
@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)NSDictionary * dataDic;
@end

@implementation MyInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self setUpNavgationView];
    [self setUpTableView];
  
}

-(void)requestTheData
{
    NSString *timestamp=[GeneralTool gettimestamp];
    
    NSDictionary *dic=@{@"UserCode":GETUSERCODE,@"Timestamp":timestamp,@"ClientType":CLIENTTYPE};
    NSString *sign=[GeneralTool GetSin:dic];
    NSString *urlString=[NSString stringWithFormat:@"User/PersonalCenter/%@/%@/%@/%@",GETUSERCODE,CLIENTTYPE,timestamp,sign];

    [RequestTool requestDataWithType:@"get" andUrlString:urlString andParameters:nil andRequestFinished:^(id responses, NSError *error) {
        [MBProgressHUD hideHUDForView:self.view];
        if ([responses[@"IsSuccess"]intValue]==1) {
            _dataDic = [responses objectForKey:@"ReturnObject"];
            [[NSUserDefaults standardUserDefaults]setObject:[_dataDic objectForKey:@"Mobile"] forKey:@"Mobile"];
            [[NSUserDefaults standardUserDefaults]synchronize];
            [self updateUI];
            [_tableView reloadData];
            //   UnreadCount 这个是消息中心的个数 UnreadUpdateCount 这个字段不知道干嘛的
        }else
        {
            [MBProgressHUD showError:@"获取个人信息失败"];
        }
        
    }];

}
-(void)updateUI
{
    UIImageView * headImageView = (UIImageView *)[_customNavView viewWithTag:555];
    UILabel * nameLabel = (UILabel *)[_customNavView viewWithTag:556];
    UILabel * userTypeName = (UILabel *)[_customNavView viewWithTag:557];
    [headImageView sd_setImageWithURL:[NSURL URLWithString:[_dataDic objectForKey:@"HeadImg"]] placeholderImage:nil options:SDWebImageRetryFailed|SDWebImageRefreshCached];
    nameLabel.text = [_dataDic objectForKey:@"NickName"];
    userTypeName.text = [_dataDic objectForKey:@"UserTypeName"];
    _leftMoneyLabel.text = [_dataDic objectForKey:@"AvailableBalance"];
    _couponLabel.text = [_dataDic objectForKey:@"CouponCount"];
    _rewardLabel.text = [_dataDic objectForKey:@"RewardCount"];
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:NO];
    _customNavView.hidden = NO;
    self.navigationController.navigationBarHidden=YES;
     //[self getCoupon];
    [self requestTheData];

}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:NO];
    _customNavView.hidden = YES;
    self.navigationController.navigationBarHidden=NO;
}
#pragma mark--自定义导航条
-(void)setUpNavgationView
{
    self.view.backgroundColor=[UIColor whiteColor];
    _customNavView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, kWidth, 100)];
    _customNavView.backgroundColor=BLUECOLOR;
    _customNavView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleBottomMargin;
    [self.view addSubview:_customNavView];
    
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(goToAlterUserInfo)];
    [_customNavView addGestureRecognizer:tap];
    
    UIImageView *logoView=[[UIImageView alloc]initWithFrame:CGRectMake(10, 35, 50, 50)];
    logoView.tag = 555;
    logoView.autoresizingMask = UIViewAutoresizingFlexibleRightMargin|UIViewAutoresizingFlexibleBottomMargin;
    [_customNavView addSubview:logoView];
    
    for (int i=0; i<2; i++) {
        UILabel *titleLabel=[[UILabel alloc]initWithFrame:CGRectMake(logoView.frame.origin.x+50+10, i*(30+5)+30, 150, 30)];
        if (i==0) {
            titleLabel.tag = 556;
        }else
        {
            titleLabel.tag = 557;
        }
        titleLabel.font = [UIFont systemFontOfSize:16];
        titleLabel.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin|UIViewAutoresizingFlexibleRightMargin;
        titleLabel.textColor=[UIColor whiteColor];
        [_customNavView addSubview:titleLabel];
    }
    
    UIButton *goToView=[[UIButton alloc]initWithFrame:CGRectMake(kWidth-10-20, 50, 20, 20)];
    [goToView setImage:[UIImage imageNamed:@"public_right"]forState:UIControlStateNormal];
    goToView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleBottomMargin;
    [goToView addTarget:self action:@selector(goToAlterUserInfo) forControlEvents:UIControlEventTouchUpInside];
    [_customNavView addSubview:goToView];
    
}
-(void)goToAlterUserInfo
{
    
}

#pragma mark--表
-(void)setUpTableView
{
    _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 100, kWidth, kHeight-100-50) style:UITableViewStyleGrouped];
    _tableView.delegate=self;
    _tableView.dataSource=self;
    //注册自定义单元格
    [_tableView registerNib:[UINib nibWithNibName:@"MyInfoTableViewCell" bundle:nil] forCellReuseIdentifier:@"custom"];
    //注册系统单元格
//    [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"default"];
    [self.view addSubview:_tableView];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 4;
}
//行高
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==3) {
        return 80;
    }
        return 44;
    
}
//行数
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section==2) {
        return 3;
    }else
    {
        return 1;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}
//区头区尾
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section==0) {
        return 70;
    }
    return 10;
}
//区头视图
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if (section==0) {
        UIView *view=[[UIView alloc]initWithFrame:CGRectMake(0, 0, kWidth, 60)];
        view.backgroundColor=[UIColor whiteColor];
        CGFloat width=kWidth/3.0;
        NSArray *textArr=@[@"账户余额",@"优惠券",@"奖励"];
        for (int i=0; i<3; i++) {
            //数量，数据从服务器返回
            UILabel *number=[[UILabel alloc]initWithFrame:CGRectMake(i*width, 10, width, 20)];
            number.textAlignment=NSTextAlignmentCenter;
            number.textColor=BLUECOLOR;
            [view addSubview:number];
            if (i==0)
            {
                _leftMoneyLabel = number;
                _leftMoneyLabel.text=@"0.00";
            }else if(i==1)
            {
                _couponLabel = number;
                _couponLabel.text = _couponCount;
            }else
            {
                _rewardLabel = number;
                _rewardLabel.text = @"0";
            }
            
            UILabel *text=[[UILabel alloc]initWithFrame:CGRectMake(i*width, 60-25, width, 20)];
            text.text=textArr[i];
            text.font = [UIFont systemFontOfSize:16];
            text.textAlignment=NSTextAlignmentCenter;
            [view addSubview:text];
            
            UIControl *control=[[UIControl alloc]initWithFrame:CGRectMake(i*width, 0, kWidth, 60)];
            control.tag=(i+1)*100;
            [control addTarget:self action:@selector(clickOnControl:) forControlEvents:UIControlEventTouchUpInside];
            [view addSubview:control];
        }
        
        return view;
    }
    return nil;
}
-(void)clickOnControl:(UIControl *)control
{
    if(control.tag == 100)
    {
        //  我的钱包界面
        WalletViewController * walletVc = [[WalletViewController alloc]init];
        walletVc.money = _leftMoneyLabel.text;
        [self.navigationController pushViewController:walletVc animated:YES];
        
    }else if (control.tag == 200)
    {
        MyCouponViewController * myCouponVc = [[MyCouponViewController alloc]init];
        myCouponVc.isUse=NO;
        [self.navigationController pushViewController:myCouponVc animated:YES];
    }else
    {
        MyRewardViewController * myRewardVc = [[MyRewardViewController alloc]init];
        [self.navigationController pushViewController:myRewardVc animated:YES];
    }
}
//#pragma mark--优惠券张数
//-(void)getCoupon
//{
//    //查看优惠券
//    [GeneralTool getMyCouponWithIsCanUse:@"1" andPageIndex:1 andReuqestBlock:^(id response, NSError *error) {
//        
//        if ([response[@"IsSuccess"]integerValue]==1) {
//             NSArray *dataArr=response[@"ReturnObject"];
//            if (dataArr.count>0) {
//                _couponCount=[NSString stringWithFormat:@"%zd",dataArr.count];
//            }
//        }
//    }];
//    
//}
//
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==3) {
        MyInfoTableViewCell *info=[tableView dequeueReusableCellWithIdentifier:@"custom" forIndexPath:indexPath];
        info.selectionStyle=UITableViewCellSelectionStyleNone;
        return info;
    }else
    {
        UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"default"];
        if (!cell)
        {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"default"];
            cell.selectionStyle=UITableViewCellSelectionStyleNone;
            cell.textLabel.font=[UIFont systemFontOfSize:13];
            
            UILabel *detail=[[UILabel alloc]initWithFrame:CGRectMake(cell.frame.size.width - 190, 7, 180, 30)];
            detail.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
            detail.textColor=[UIColor lightGrayColor];
            detail.font=[UIFont systemFontOfSize:13];
            detail.textAlignment=NSTextAlignmentRight;
            detail.tag = 111;
            [cell addSubview:detail];
            
            UIView * bageView = [[UIView alloc]initWithFrame:CGRectMake(25-2.5, 0, 5, 5)];
            bageView.layer.cornerRadius = 2.5;
            bageView.layer.masksToBounds = YES;
            bageView.tag = 222;
            bageView.backgroundColor = [UIColor redColor];
            [cell.imageView addSubview:bageView];
        }
        UILabel * detail = (UILabel *)[cell viewWithTag:111];
        UIView * bageView = (UIView *)[cell.imageView viewWithTag:222];
        bageView.hidden = YES;
        if (indexPath.section==0)
        {
            cell.textLabel.text=@"我的钱包";
            cell.imageView.image=[UIImage imageNamed:@"money_pack_icon"];
            detail.text=@"余额、优惠券等 >";
            
        }else if (indexPath.section==1) {
            cell.textLabel.text=@"消息中心";
            cell.imageView.image=[UIImage imageNamed:@"msg_center_icon"];
            detail.text=@"与我相关的消息 >";
            if ([_dataDic objectForKey:@"UnreadCount"]&&[_dataDic objectForKey:@"UnreadCount"]!=0)
            {
                bageView.hidden = NO;
            }
        }else
        {
            NSArray *titleArr=@[@"地址管理",@"帮助与反馈",@"关于净净"];
            NSArray *detailArr=@[@"取送衣地址 >",@"常见问题，意见反馈等 >",@"版本信息，分享好友 >"];

            NSArray *imageArr=@[@"address_center_icon",@"help_and_suggest_icon",@"home_down"];
            cell.textLabel.text=titleArr[indexPath.row];
            cell.imageView.image=[UIImage imageNamed:imageArr [indexPath.row]];
            detail.text=detailArr[indexPath.row];
        }
        return cell;
    }
}
// 选中某一行
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 0)
    {
        //  我的钱包界面
        WalletViewController * walletVc = [[WalletViewController alloc]init];
        walletVc.money = _leftMoneyLabel.text;
        [self.navigationController pushViewController:walletVc animated:YES];
    }
    if(indexPath.section == 1)
    {
        MessageCenterViewController * messageCenter = [[MessageCenterViewController alloc]init];
        [self.navigationController pushViewController:messageCenter animated:YES];
    }
    if(indexPath.section == 2&&indexPath.row==0)
    {
        //地址管理
        MyAddressViewController * addressVc = [[MyAddressViewController alloc]init];
        [self.navigationController pushViewController:addressVc animated:YES];
    }
    if(indexPath.section == 2&&indexPath.row==1)
    {
        //帮助与反溃
        AssistViewController * assistVc = [[AssistViewController alloc]init];
        [self.navigationController pushViewController:assistVc animated:YES];
    }
    if(indexPath.section == 2&&indexPath.row==2)
    {
        //关于净净
        AboutJingjingViewController * aboutVc = [[AboutJingjingViewController alloc]init];
        [self.navigationController pushViewController:aboutVc animated:YES];
    }
    if (indexPath.section == 3)
    {
        NSDate * currentDate = [NSDate dateWithTimeIntervalSinceNow:0];
        NSInteger hour = [currentDate hour];
        if (hour>=9&&hour<=21)
        {
            [self callPhoneWithPhoneNum:@"40000-123-299"];
        }else
        {
            [ZMTool showAlertWithDifferentVersioninWhichViewController:self withTitle:@"温馨提示" andMessage:@"请于上午9:00至晚间21:00时间范围内拨打客服电话" andSureTitle:@"知道了" andCancleTitle:nil isDelegate:NO andSureBlock:nil andCancleBlock:nil];
        }
    }
}
- (void)callPhoneWithPhoneNum:(NSString *)phoneNumber
{
    NSMutableString * str=[[NSMutableString alloc] initWithFormat:@"tel:%@",phoneNumber];
    UIWebView * callWebview = [[UIWebView alloc] init];
    [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
    [self.view addSubview:callWebview];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
